package com.banciyuan.bcywebview.biz.main;

import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;
import android.text.TextUtils;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.ImageView;

import com.baidu.mobstat.StatService;
import com.banciyuan.bcywebview.R;
import com.banciyuan.bcywebview.base.activity.BaseActivity;
import com.banciyuan.bcywebview.base.factory.FragmentFactory;
import com.banciyuan.bcywebview.base.fragment.BaseContainerFragment;
import com.banciyuan.bcywebview.base.helper.FlagUtils;
import com.banciyuan.bcywebview.base.helper.data.UserDataHelper;
import com.banciyuan.bcywebview.base.helper.push.PushDataHelper;
import com.banciyuan.bcywebview.base.util.BaseObserver;
import com.banciyuan.bcywebview.base.util.BaseWatcher;
import com.banciyuan.bcywebview.base.view.toast.MyToast;
import com.banciyuan.bcywebview.biz.detail.atperson.AtPersonProperties;
import com.banciyuan.bcywebview.biz.main.mineinfo.MineInfoFragment2;
import com.banciyuan.bcywebview.utils.constants.EventConstants;
import com.banciyuan.bcywebview.utils.constants.MyConstants;
import com.banciyuan.bcywebview.utils.intent.gotoUtil;
import com.banciyuan.bcywebview.utils.sp.SPConstant;
import com.banciyuan.bcywebview.utils.sp.SPHelper;
import com.banciyuan.bcywebview.utils.update.UpdateHelper;
import com.tencent.bugly.crashreport.CrashReport;

import java.util.HashMap;
import java.util.Map;

import de.greenrobot.daoexample.model.NotificationData;

public class MainActivity extends BaseActivity implements OnClickListener, BaseWatcher {

    private int fragmentPostion = 5;
    private FragmentManager fragmentManager;
    private ImageView mMainPageImg;
    private ImageView mDiscoverImg;
    private ImageView mGroupImg;
    private ImageView mMessageImg;
    private ImageView mMineImg;
    private View mBanGuideLayout;
    protected final Handler mHandler = new Handler();
    private boolean mClickBack = false;
    private Runnable mResetBackRunnable = new Runnable() {
        @Override
        public void run() {
            mClickBack = false;
        }
    };

    private Map<String, Fragment> fmap = new HashMap<>();

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main_layout);
        initArgs();
        initUi();
        initAction();
        initData();
        showGuideBanLayout();
    }

    @Override
    protected void onNewIntent(Intent intent) {
        super.onNewIntent(intent);
        try {
            recreate();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    private void showGuideBanLayout() {
        if (!TextUtils.isEmpty(UserDataHelper.getInstance(this).getToken())) {
            if (SPHelper.getBoolean(this, SPConstant.SHOW_BAN_TIMELINE_GUIDE, true)) {
                mBanGuideLayout.setVisibility(View.VISIBLE);
                mBanGuideLayout.findViewById(R.id.ban_guide_letter).setOnClickListener(this);
            } else {
                mBanGuideLayout.setVisibility(View.GONE);
            }
        }
    }


    @Override
    protected void onResume() {
        String pushvalue = SPHelper.getString(this, SPConstant.PUSHVALUE, "");
        if (!TextUtils.isEmpty(pushvalue)) {
            PushDataHelper.processPushData(MainActivity.this, pushvalue);
            SPHelper.putString(this, SPConstant.PUSHVALUE, "");
        }
        resetBottomTab();
        super.onResume();
    }

    public void resetBottomTab() {
        if (FlagUtils.hasNewNotify()) {
            if (fragmentPostion == 4)
                mMineImg.setImageResource(R.drawable.main_mine_point_pink);
            else mMineImg.setImageResource(R.drawable.main_mine_point_black);
        } else {
            if (fragmentPostion == 4) mMineImg.setImageResource(R.drawable.main_mine_pink);
            else mMineImg.setImageResource(R.drawable.main_mine_black);
        }
    }


    @Override
    public void onDestroy() {
        super.onDestroy();
        BaseObserver.getInstance().removeWatcher(MainActivity.class);
        AtPersonProperties.getInstance().clearPersonNames();
    }

    @Override
    protected void initArgs() {
        BaseObserver.getInstance().addWatcher(MainActivity.class, this);
        new UpdateHelper(this).doAutoUpdate();
        CrashReport.setUserId(UserDataHelper.getInstance(this).getUid());
        fragmentManager = getSupportFragmentManager();
    }

    @Override
    protected void initUi() {
        mMainPageImg = (ImageView) findViewById(R.id.main_bottom_mainpage_tv);
        mDiscoverImg = (ImageView) findViewById(R.id.main_bottom_discover_tv);
        mGroupImg = (ImageView) findViewById(R.id.main_bottom_group_tv);
        mMessageImg = (ImageView) findViewById(R.id.main_bottom_message_tv);
        mMineImg = (ImageView) findViewById(R.id.main_bottom_mine_tv);
        mBanGuideLayout = findViewById(R.id.ban_guide_layout);
    }

    @Override
    protected void initAction() {
        mMainPageImg.setOnClickListener(this);
        mDiscoverImg.setOnClickListener(this);
        mGroupImg.setOnClickListener(this);
        mMessageImg.setOnClickListener(this);
        mMineImg.setOnClickListener(this);
    }

    @Override
    protected void initData() {
        selectItem(0);
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.main_bottom_mainpage_tv:
                selectItem(0);
                break;
            case R.id.main_bottom_discover_tv:
                selectItem(1);
                break;
            case R.id.main_bottom_group_tv:
                selectItem(2);
                break;
            case R.id.main_bottom_message_tv:
                selectItem(3);
                break;
            case R.id.main_bottom_mine_tv:
                selectItem(4, UserDataHelper.getInstance(this).getUid());
                break;
            case R.id.ban_guide_letter:
                SPHelper.putBoolean(this, SPConstant.SHOW_BAN_TIMELINE_GUIDE, false);
                mBanGuideLayout.setVisibility(View.GONE);
                break;
            default:
                break;
        }
    }

    @Override
    public void onBackPressed() {
        if (fragmentPostion == 0) {
            if (!getSupportFragmentManager().popBackStackImmediate()) {
                if (!mClickBack) {
                    MyToast.show(this, getString(R.string.more_click_exit));
                    mClickBack = true;
                    mHandler.postDelayed(mResetBackRunnable, 2000);
                } else {
                    finish();
                }
            }
        } else {
            selectItem(0);
        }
    }

    @Override
    public void onEventHappen(int eventCode, String message, Object object) {
        if (eventCode == BaseObserver.MESSAGE_EVENT) {
            NotificationData notificationData = (NotificationData) object;
            //处理消息提醒
            FlagUtils.storeNotificationData(notificationData);
            FlagUtils.ifMimeUpdate = true;
            resetBottomTab();
        }
    }


    private void selectItem(int position) {
        selectItem(position, null);
    }

    private void selectItem(int position, String message) {
        try {
            if (fragmentPostion == position) {
                refreshPage(position);
                return;
            }
            setSelected(fragmentPostion, false);
            setSelected(position, true);
            fragmentPostion = position;

            Fragment newFragment = fragmentManager.findFragmentByTag(MyConstants.MAIN_FRAGMENT_TAG[position]);
            FragmentTransaction ft = fragmentManager.beginTransaction();

            if (fmap != null) {
                for (Fragment nowFragment : fmap.values()) {
                    if (nowFragment != null && nowFragment.isAdded())
                        ft.hide(nowFragment);
                }
            }

            if (newFragment == null) {
                newFragment = FragmentFactory.createFragment(position);
                if (!TextUtils.isEmpty(message)) {
                    Bundle bundle = new Bundle();
                    bundle.putString(gotoUtil.INTENT_VALUE_ONE, message);
                    newFragment.setArguments(bundle);
                }
                fmap.put(MyConstants.MAIN_FRAGMENT_TAG[position], newFragment);
                ft.add(R.id.main_content_fly, newFragment, MyConstants.MAIN_FRAGMENT_TAG[position]);
                ft.show(newFragment);
            } else ft.show(newFragment);
            if (position == 4) {
                ((MineInfoFragment2) newFragment).renderUi();
            }

            ft.commit();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    private void setSelected(int position, Boolean colored) {
        switch (position) {
            case 0:
                if (colored) {
                    mMainPageImg.setImageResource(R.drawable.main_mainpage_pink);
                } else {
                    mMainPageImg.setImageResource(R.drawable.main_mainpage_black);
                }
                StatService.onEvent(this, EventConstants.MAIN_ID, EventConstants.MAIN_EVENT);
                break;
            case 1:
                if (colored) {
                    mDiscoverImg.setImageResource(R.drawable.main_discover_pink);
                } else {
                    mDiscoverImg.setImageResource(R.drawable.main_discover_black);
                }
                StatService.onEvent(this, EventConstants.DISCOVER_ID, EventConstants.DISCOVER_EVENT);
                break;
            case 2:
                if (colored) {
                    mGroupImg.setImageResource(R.drawable.main_group_pink);
                } else {
                    mGroupImg.setImageResource(R.drawable.main_group_black);
                }
                StatService.onEvent(this, EventConstants.GROUP_ID, EventConstants.GROUP_EVENT);
                break;
            case 3:
                if (colored) {
                    mMessageImg.setImageResource(R.drawable.main_daily_hover);
                } else {
                    mMessageImg.setImageResource(R.drawable.main_daily);
                }
                StatService.onEvent(this, EventConstants.DAILY_ID, EventConstants.DAILY_EVENT);
                break;
            case 4:
                if (colored) {
                    if (FlagUtils.hasNewNotify() && !TextUtils.isEmpty(UserDataHelper.getInstance(this).getToken()))
                        mMineImg.setImageResource(R.drawable.main_mine_point_pink);
                    else mMineImg.setImageResource(R.drawable.main_mine_pink);
                } else {
                    if (FlagUtils.hasNewNotify() && !TextUtils.isEmpty(UserDataHelper.getInstance(this).getToken()))
                        mMineImg.setImageResource(R.drawable.main_mine_point_black);
                    else mMineImg.setImageResource(R.drawable.main_mine_black);
                }
                StatService.onEvent(this, EventConstants.MINE_ID, EventConstants.MINE_EVENT);
                break;
            default:
                break;
        }

    }


    private void refreshPage(int position) {
        try {
            BaseContainerFragment newFragment = (BaseContainerFragment) fragmentManager.
                    findFragmentByTag(MyConstants.MAIN_FRAGMENT_TAG[position]);
            newFragment.selfUpdateData();
        } catch (Exception e) {
        }
    }


    @Override
    protected void onSaveInstanceState(Bundle outState) {

    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        for (Fragment f : fmap.values()) {
            f.onActivityResult(requestCode, resultCode, data);
        }
    }

}